package net.nycjava.skylight1.dependencyinjection;

import static java.lang.String.format;

//TODO javadoc
class ImplementationClassSingletonObjectSource<T, S extends T> extends ObjectSource<T> {

    private Class<S> clazz;

    private S singleObject;

    ImplementationClassSingletonObjectSource(Class<S> aClass) {
        if (aClass.isInterface()) {
            throw new IllegalArgumentException(format(
                    "Provided class must be a concrete type, however %s is an interface.", aClass.getName()));
        }

        clazz = aClass;
    }

    @Override
    public T getObject(DependencyInjector injector) {
        if (singleObject == null) {
            try {
                singleObject = clazz.newInstance();
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            }
            injector.injectDependenciesForClassHierarchy(singleObject);
        }
        return singleObject;
    }
}